<template>
  <div class="app-container">
    <div class="filter-container">
      <el-input
        v-model="listQuery.roleName"
        clearable
        :placeholder="$t('table.role.name')"
        style="width: 200px;"
        class="filter-item"
      />
      <el-select
        v-model="listQuery.status"
        class="filter-item"
        :placeholder="$t('table.status')"
        clearable
      >
        <el-option
          v-for="item in roleStatus"
          :key="item.key"
          :label="$t(item.display_name)"
          :value="item.key"
        />
      </el-select>
      <searchBtn @handle="handleFilter" />
      <addBtn auth="sys:role:add" @handle="handleBtn([1])" />
    </div>
    <el-table
      v-loading="listLoading"
      :data="dataList"
      row-key="roleId"
      border
      fit
      highlight-current-row
      style="width: 100%;"
      :height="tableHeight"
    >
      <el-table-column
        :label="$t('table.id')"
        align="center"
        type="index"
        style="width:50px;"
        min-width="12%"
      >
        <template slot-scope="{row}">{{ row.roleId }}</template>
      </el-table-column>
      <el-table-column
        :label="$t('table.role.name')"
        min-width="15%"
        align="center"
        prop="roleName"
      >
        <template slot-scope="{row}">
          <span>{{ row.roleName }}</span>
        </template>
      </el-table-column>
      <el-table-column
        :label="$t('table.role.roleSign')"
        min-width="15%"
        align="center"
        prop="roleSign"
      >
        <template slot-scope="{row}">
          <span>{{ row.roleSign }}</span>
        </template>
      </el-table-column>
      <el-table-column :label="$t('table.status')" min-width="15%" align="center" prop="status">
        <template slot-scope="{row}">
          <span v-if="row.status==='0'" style="color:red;">{{ $t('table.status1') }}</span>
          <span v-else style="color:blue;">{{ $t('table.status2') }}</span>
        </template>
      </el-table-column>

      <el-table-column
        :label="$t('table.actions')"
        align="center"
        min-width="25%"
        class-name="small-padding fixed-width"
      >
        <template slot-scope="{row}">
          <groupBtn :auths="btnGroup" :param="row" @handle="handleBtn(arguments)" />
        </template>
      </el-table-column>
    </el-table>

    <el-dialog :title="$t(textMap[dialogStatus])" :visible.sync="dialogFormVisible">
      <el-form
        ref="dataForm"
        :rules="rules"
        :model="temp"
        label-position="left"
        label-width="100px"
        style="width: 500px; margin-left:50px;"
      >
        <el-form-item :label="$t('table.role.name')" prop="roleName">
          <el-input v-model="temp.roleId" style="display:none;" />
          <el-input v-model="temp.roleName" />
        </el-form-item>
        <el-form-item :label="$t('table.role.roleSign')" prop="roleSign">
          <el-input v-model="temp.roleSign" />
        </el-form-item>
        <el-form-item :label="$t('table.status')" prop="status">
          <el-select v-model="temp.status" class="filter-item">
            <el-option
              v-for="item in roleStatus"
              :key="item.key"
              :label="$t(item.display_name)"
              :value="item.key"
            />
          </el-select>
        </el-form-item>
      </el-form>
      <div slot="footer" class="dialog-footer">
        <el-button @click="dialogFormVisible = false">{{ $t('table.cancel') }}</el-button>
        <el-button type="primary" @click="createData()">{{ $t('table.confirm') }}</el-button>
      </div>
    </el-dialog>
    <el-dialog :title="$t(textMap[dialogStatus])" width="30%" :visible.sync="dialogPermission">
      <el-scrollbar style="height:50vh">
        <el-tree
          :data="menuData"
          show-checkbox
          default-expand-all
          node-key="id"
          ref="tree"
          highlight-current
          :props="defaultProps"
        ></el-tree>
      </el-scrollbar>
      <div slot="footer" class="dialog-footer">
        <el-button @click="dialogPermission = false">{{ $t('table.cancel') }}</el-button>
        <el-button type="primary" @click="createData()">{{ $t('table.confirm') }}</el-button>
      </div>
    </el-dialog>
  </div>
</template>

<script>
import {
  fetchRoleList,
  updateRole,
  findByRoleId,
  deleteByRoleId,
  fetchMenuList
} from '@/api/system'
import groupBtn from '@/components/buttonGroup/groupBtn'
import searchBtn from '@/components/buttonGroup/searchBtn'
import addBtn from '@/components/buttonGroup/addBtn'
import { createTree } from '@/utils/utils'
const roleStatus = [
  { key: '0', display_name: 'table.status1' },
  { key: '1', display_name: 'table.status2' }
]
export default {
  name: 'Role',
  components: { groupBtn, searchBtn, addBtn },
  data() {
    return {
      tableHeight: window.innerHeight - 200,
      btnGroup: [
        {
          id: 2,
          auth: 'sys:role:edit',
          btnType: 'success',
          name: 'table.edit'
        },
        {
          id: 3,
          auth: 'sys:role:delete',
          btnType: 'danger',
          name: 'table.delete'
        },
        {
          id: 4,
          auth: 'sys:role:grantPermissions',
          btnType: 'primary',
          name: 'table.role.permissions'
        }
      ],
      dataList: [],
      roleStatus,
      listLoading: true,
      listQuery: {
        roleName: undefined
      },
      temp: {},
      dialogFormVisible: false,
      dialogPermission: false,
      dialogStatus: '',
      textMap: {
        update: 'table.role.edit',
        create: 'table.role.create',
        permission: 'table.role.permissions'
      },
      rules: {
        roleName: [
          {
            required: true,
            message: this.$t('table.role.nameRule'),
            trigger: 'blur'
          }
        ]
      },
      downloadLoading: false,
      defaultProps: {
        children: 'children',
        label: 'name'
      },
      menuData: []
    }
  },
  computed: {},
  watch: {},
  created() {
    this.getList()
    this.loadDepts()
  },
  methods: {
    handleFilter() {
      this.getList()
    },
    getList() {
      this.listLoading = true
      fetchRoleList(this.listQuery).then(response => {
        this.dataList = response.content
        setTimeout(() => {
          this.listLoading = false
        }, 1000)
      })
    },
    resetTemp() {
      this.temp = {
        roleId: undefined,
        roleName: '',
        status: '0'
      }
    },
    createData() {
      this.$refs['dataForm'].validate(valid => {
        if (valid) {
          updateRole(this.temp).then(data => {
            if (this.temp.roleId) {
              this.dataList.forEach(item => {
                if (item.roleId === this.temp.roleId) {
                  item.roleName = this.temp.roleName
                  item.roleSign = this.temp.roleSign
                  item.status = this.temp.status
                }
              })
            } else {
              this.temp.roleId = data.content.roleId
              this.dataList.push(this.temp)
            }
            this.dialogFormVisible = false
            this.$message({
              type: 'success',
              message: data.msg
            })
          })
        }
      })
    },
    /** 按钮回调 **/
    handleBtn: function(param) {
      const id = param[0]
      const row = param[1]
      this.resetTemp()
      if (id === 1) {
        this.resetTemp()
        this.dialogStatus = 'create'
        this.dialogFormVisible = true
        this.$nextTick(() => {
          this.$refs['dataForm'].clearValidate()
        })
      } else if (id === 2) {
        findByRoleId(row.roleId).then(data => {
          const content = data.content
          this.temp = JSON.parse(JSON.stringify(content))
          this.dialogStatus = 'update'
          this.dialogFormVisible = true
          this.$nextTick(() => {
            this.$refs['dataForm'].clearValidate()
          })
        })
      } else if (id === 3) {
        this.$confirm('此操作将删除角色, 是否继续?', '提示', {
          confirmButtonText: '确定',
          cancelButtonText: '取消',
          type: 'warning'
        })
          .then(() => {
            deleteByRoleId(row.roleId).then(data => {
              this.dataList.splice(
                this.dataList.findIndex(item => item.roleId === row.roleId),
                1
              )
              this.$message({
                type: 'success',
                message: '删除成功!'
              })
            })
          })
          .catch(() => {
            this.$message({
              type: 'info',
              message: '已取消删除'
            })
          })
      } else if (id === 4) {
        this.dialogStatus = 'permission'
        this.dialogPermission = true
      }
    },
    loadDepts() {
      fetchMenuList({}).then(response => {
        const menus = response.content
        this.menuData = createTree(menus, 'menuId')
      })
    }
  }
}
</script>
<style scoped>
.el-dialog__body {
  height: 50vh;
  overflow: auto;
}
</style>